package com.wuzhen.wzzt.core.configurer;

import com.wuzhen.wzzt.core.constant.ProjectConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.net.Inet4Address;
import java.net.UnknownHostException;

/**
 * @author zhengzheng
 * @Description:Swagger2 配置文件
 * @date 2022年3月16日 11:28
 */
@Configuration
@EnableSwagger2
public class SwaggerConfigurer implements ApplicationListener<WebServerInitializedEvent> {

    private static Logger logger = LoggerFactory.getLogger(SwaggerConfigurer.class);


    @Value("${wuzhen.api.version}")
    private String version;

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(ProjectConstant.CONTROLLER_PACKAGE))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("wzzt-api 使用Swagger2构建RESTful APIs")
                .version(version)
                .build();
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent event) {
        try {
            // 获取IP
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            // 获取端口号
            int port = event.getWebServer().getPort();
            // 获取应用名
            String applicationName = event.getApplicationContext().getApplicationName();
            // 打印 swagger 文档地址
            logger.info("项目启动启动成功！swagger 接口文档地址: https://" + hostAddress + ":" + port + applicationName + "/swagger-ui.html");
            // 打印 swagger2 文档地址
            logger.info("项目启动启动成功！swagger2 接口文档地址: https://" + hostAddress + ":" + port + applicationName + "/doc.html");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }
}
